package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private HttpSession session;

    @Autowired(required = false)
    private UserService userService;


    //处理发送短信的请求
    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        //1.接收手机号封装User对象
        //2.生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码: "+code);
        //3.发送手机验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //4.将生成的验证码存储到session中(手机号为key,验证码作为value)
        session.setAttribute(user.getPhone(),code);
        //5.返回数据,输出成功
        return R.success("发送验证码短信成功");
    }

    //处理用户端登入的请求
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map){
        //1.接收数据封装到Map<String, String> map
        String phone = map.get("phone");//用户手机号
        String userCode = map.get("code");//验证码

        //2.从session中获取存储的验证码
        String sessionCode = (String) session.getAttribute(phone);

        //3.调用业务层进行登入操作,返回登入的用户对象
        User loginUser = userService.login(phone, userCode, sessionCode);
        if (loginUser!=null){
            //4.登入用户有效,写入用户的idsession(key="user")
            session.setAttribute("user",loginUser.getId());
            //登入成功后,删除session的验证码
            session.removeAttribute(phone);
            //返回成功数据
            return R.success(loginUser);
        }

        //5.返回失败数据
        return R.error("登入失败");
    }

}
